package com.timedomain.him.remake;

import android.annotation.SuppressLint;
import android.app.Application;
import android.content.Context;
import android.util.AndroidRuntimeException;

import com.timedomain.him.remake.utils.*;
import com.un4seen.bass.BASS;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Pattern;

import uk.co.chrisjenx.calligraphy.CalligraphyConfig;


public class Program extends Application {



    public static InputStream openAsset(Context ctx,String datapackPath) throws IOException {
        var dataEntry = getDataPack(ctx).get(datapackPath);
        if(dataEntry == null){
            throw new AndroidRuntimeException("数据包中找不到文件: "+datapackPath);
        }
        if(dataEntry.prefix.startsWith("@")){
            return ctx.getAssets().open("data/"+dataEntry.hash);
        }
        else if(dataEntry.prefix.startsWith("~")){
            return new FileInputStream(dataEntry.hash);
        }
        throw new IllegalStateException("无效的数据包前缀名："+dataEntry.prefix);
    }


    public static HashMap<String, DataPackManager.DataPackEntry> getDataPack(Context ctx){
        return DataPackManager.getDataPack(ctx);
    }

    public static List<DataPackManager.DataPackEntry> getDataEntries(Context ctx){
        return DataPackManager.getDataEntries(ctx);
    }


    public static boolean isColdBoot = false;

    @Override
    public void onCreate() {
        super.onCreate();
        isColdBoot = true;
        CalligraphyConfig.initDefault(new CalligraphyConfig.Builder()
                .setDefaultFontPath("fonts/normal.ttf")
                .setFontAttrId(R.attr.fontPath)
                .disableCustomViewInflation()
                .build()
        );
        if(!BASS.BASS_Init(-1,48000,BASS.BASS_DEVICE_SPEAKERS)){
            int code = BASS.BASS_ErrorGetCode();
            HLog.e("libbass", "Cannot init bass: "+ code);
            //throw new AndroidRuntimeException("Cannot load bass library: reason code = "+code);
        }
        AppSettings.loadSettings(this);
        DB.ensureDBInited(this);
        DataPackManager.initDataPackSystem(this);
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }
}
